import { defineStore } from 'pinia';
import { login, logout, getUserInfo, type LoginParams, type LoginResult } from '@/api/auth';
import { router } from '@/router';

interface UserState {
  token: string;
  userInfo: any;
  permissions: string[];
  tenantId: string; // 租户ID
}

export const useUserStore = defineStore('user', {
  state: (): UserState => ({
    token: localStorage.getItem('token') || '',
    userInfo: JSON.parse(localStorage.getItem('userInfo') || 'null'),
    permissions: [],
    tenantId: localStorage.getItem('tenantId') || '',
  }),

  getters: {
    isLogin: (state) => !!state.token,
    username: (state) => state.userInfo?.FNAME || state.userInfo?.FCODE || '',
    userId: (state) => state.userInfo?.FMID || '',
    // 获取租户ID
    getTenantId: (state) => state.tenantId || state.userInfo?.FTNID || '*',
  },

  actions: {
    /**
     * 登录
     */
    async login(params: LoginParams) {
      try {
        const result = await login(params);
        
        // 注意：登录接口返回的 token 在 context 中，需要从响应头或其他位置获取
        // 这里先生成一个临时 token，实际应根据后端返回调整
        const token = result.token || `token_${Date.now()}`;
        
        // 提取租户ID
        const tenantId = result.userInfo?.FTNID || '*';
        
        this.token = token;
        this.userInfo = result.userInfo;
        this.tenantId = tenantId;
        this.permissions = [];

        // 保存到 localStorage
        localStorage.setItem('token', token);
        localStorage.setItem('userInfo', JSON.stringify(result.userInfo));
        localStorage.setItem('tenantId', tenantId);

        return result;
      } catch (error) {
        return Promise.reject(error);
      }
    },

    /**
     * 退出登录
     */
    async logout() {
      try {
        await logout();
      } catch (error) {
        console.error('退出登录失败:', error);
      } finally {
        this.token = '';
        this.userInfo = null;
        this.tenantId = '';
        this.permissions = [];
        localStorage.removeItem('token');
        localStorage.removeItem('userInfo');
        localStorage.removeItem('tenantId');
        router.push('/login');
      }
    },

    /**
     * 获取用户信息
     */
    async getUserInfo() {
      try {
        const userInfo = await getUserInfo();
        this.userInfo = userInfo;
        localStorage.setItem('userInfo', JSON.stringify(userInfo));
        return userInfo;
      } catch (error) {
        return Promise.reject(error);
      }
    },
  },
});
